package com.jzh.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jzh.dao.RoleDao;
import com.jzh.entity.PageResult;
import com.jzh.entity.QueryPageBean;
import com.jzh.pojo.Role;
import com.jzh.service.RoleService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色实现
 * @author jzh971018
 */
@Service(version = "1.0.0")
@Transactional
public class RoleServiceImpl implements RoleService{

    @Resource
    private RoleDao roleDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        //查询条件
        String queryString = queryPageBean.getQueryString();
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Role> rows = page.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    @Override
    public void edit(Role role, Integer[] permissionIds) {
        roleDao.edit(role);
        roleDao.deleteAssocication(role.getId());

        this.setRoleAndPermission(role.getId(),permissionIds);
    }

    @Override
    public void add(Role role, Integer[] permissionIds) {
        roleDao.add(role);
        this.setRoleAndPermission(role.getId(),permissionIds);
    }

    @Override
    public void deleteById(Integer id) {
        Long count = roleDao.findCountByRoleId(id);
        if (count > 0){
            new RuntimeException();
        }
        roleDao.deleteAssocication(id);
        roleDao.deleteById(id);
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    public void setRoleAndPermission(Integer roleId,Integer[] permissionIds){
        if (permissionIds.length > 0 && permissionIds != null){
            for (Integer permissionId : permissionIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("permissionId",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }
}
